package pro.softzhang.algo.lc0;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 51. N 皇后
 * https://leetcode.cn/problems/n-queens/
 */
public class LC51_NQueens {
    public static void main(String[] args) {

    }

    /**
     *
     */
    static
    class Solution {
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> solutions = new ArrayList<>();
            int[] queens = new int[n];
            boolean[] cols = new boolean[n], diag1 = new boolean[n * 2 - 1], diag2 = diag1;

            dfs(0, queens, cols, diag1, diag2, solutions);

            return solutions;
        }

        private void dfs(int i, int[] queens, boolean[] cols, boolean[] diag1, boolean[] diag2, List<List<String>> solutions) {
            int n = cols.length;
            if (i == n) {
                List<String> board = new ArrayList<>();
                for (int c : queens) {
                    char[] row = new char[n];
                    Arrays.fill(row, '.');
                    row[c] = 'Q';
                    board.add(new String(row));
                }
                solutions.add(board);
                return;
            }

            for (int c = 0; c < n; c++) {
                int rc = i - c + n - 1;
                if (!cols[c] && !diag1[i + c] && !diag2[rc]) {
                    queens[i] = c;
                    cols[c] = diag1[i + c] = diag2[rc] = true;
                    dfs(i + 1, queens, cols, diag1, diag2, solutions);
                    cols[c] = diag1[i + c] = diag1[rc] = false;
                }
            }
        }
    }
}
